package com.leetcode.Offer;

import java.util.*;

public class JZ32_III {
    public List<List<Integer>> levelOrder(TreeNode root) {

        //广度搜索
        if (root == null) {
            return new ArrayList<>();
        }
        Queue<TreeNode> treeNodeQueue = new LinkedList<>();
        treeNodeQueue.add(root);

        List<List<Integer>> lists = new ArrayList<>();
        int a = 0;
        while (!treeNodeQueue.isEmpty()) {
            int size = treeNodeQueue.size();//记录层次节点数
            List<Integer> list = new ArrayList<>();

            for (int i = size; i > 0; i--) {
                TreeNode peek = treeNodeQueue.poll();
                list.add(peek.val);
                if (peek.left != null) {
                    treeNodeQueue.add(peek.left);
                }
                if (peek.right != null) {
                    treeNodeQueue.add(peek.right);
                }
            }
            if (a++ % 2 == 1) {
                Collections.reverse(list);
            }
            lists.add(list);

        }
        return lists;

    }
}
